package com.pengtu.service.app;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.pengtu.dao.Page;
import com.pengtu.dao.QueryFilter;
import com.pengtu.dao.app.AuthorityDao;
import com.pengtu.dao.app.DepartmentDao;
import com.pengtu.dao.app.ExternalOrganizationDao;
import com.pengtu.dao.app.InsideOrganizationDao;
import com.pengtu.dao.app.OrganizationDao;
import com.pengtu.dao.app.RoleDao;
import com.pengtu.dao.app.UserDao;
import com.pengtu.dao.app.UserDepartmentDao;
import com.pengtu.dao.app.UserQualificationDao;
import com.pengtu.entity.app.Authority;
import com.pengtu.entity.app.Department;
import com.pengtu.entity.app.ExternalOrganization;
import com.pengtu.entity.app.InsideOrganization;
import com.pengtu.entity.app.Organization;
import com.pengtu.entity.app.Role;
import com.pengtu.entity.app.User;
import com.pengtu.entity.app.UserDepartment;
import com.pengtu.entity.app.UserQualification;
import com.pengtu.security.SpringSecurityUtils;
import com.pengtu.service.ServiceException;

/**
 * 安全相关实体的管理类, 包括用户,角色,资源与授权类.
 * 
 * @author calvin
 */
// Spring Bean的标识.
@Component
// 默认将类中的所有函数纳入事务管理.
@Transactional
public class AccountManager {

	private static Logger logger = LoggerFactory
			.getLogger(AccountManager.class);
	private UserDao userDao;
	private RoleDao roleDao;
	private AuthorityDao authorityDao;
	private DepartmentDao departmentDao;
	private OrganizationDao organizationDao;
	private InsideOrganizationDao insideOrganizationDao;
	private ExternalOrganizationDao externalOrganizationDao;
	private UserDepartmentDao userDepartmentDao;
	private UserQualificationDao userQuaDao;

	// -- User Manager --//
	@Transactional(readOnly = true)
	public User getUser(String id) {
		return userDao.get(id);
	}

	@Transactional(readOnly = true)
	public List<User> get() {
		return userDao.getAll();
	}

	public void saveUser(User entity) {
		userDao.save(entity);
	}

	/**
	 * 删除用户,如果尝试删除超级管理员将抛出异常.
	 */
	public void deleteUser(String id) {
		if (isSupervisor(id)) {
			logger.warn("操作员{}尝试删除超级管理员用户",
					SpringSecurityUtils.getCurrentUserName());
			throw new ServiceException("不能删除超级管理员用户");
		}
		userDao.delete(id);
	}

	/**
	 * 判断是否超级管理员.
	 */
	private boolean isSupervisor(String id) {
		return id.equals("1");
	}

	/**
	 * 使用属性过滤条件查询用户.
	 */
	@Transactional(readOnly = true)
	public List<User> searchUser(QueryFilter filter) {
		return userDao.find(filter);
	}

	/**
	 * 查找同一角色的用户
	 */
	@Transactional(readOnly = true)
	public List<User> searchRoleUser(String roleId) {
		String hql = "select u  from User u join u.roleList role WHERE role.id = '"+roleId+"' and u.organization.type= '"+ 0 +"' order by   u.createDate asc ";
		return userDao.find(hql);
	}

	/**
	 * 使用属性过滤条件查询用户.
	 */
	@Transactional(readOnly = true)
	public Page<User> searchUser(Page<User> page, QueryFilter filter) {
		return userDao.findPage(page, filter);
	}

	@Transactional(readOnly = true)
	public User findUserByLoginName(String userName) {
		return userDao.findUniqueBy("userName", userName);
	}

	@Transactional(readOnly = true)
	public User findUserByEmail(String email) {
		return userDao.findUniqueBy("email", email);
	}

	@Transactional(readOnly = true)
	public List<User> getUserByRoleId(String groupId) {
		String hql = "select vo from User vo join vo.roleList roles where roles.roleName=?";
		Object[] objs = { groupId };
		return userDao.find(hql, objs);
	}

	@Transactional(readOnly = true)
	public List<User> findUsersByOrgId(String orgId) {
		Organization organization = organizationDao.get(orgId);
		return organization.getUserList();
	}

	/**
	 * 使用属性过滤条件查询用户.
	 */
	@Transactional(readOnly = true)
	public Page<Role> searchRole(final Page<Role> page,
			final QueryFilter filters) {
		return roleDao.findPage(page, filters);
	}

	/**
	 * 检查用户名是否唯一.
	 * 
	 * @return loginName在数据库中唯一或等于oldLoginName时返回true.
	 */
	@Transactional(readOnly = true)
	public boolean isLoginNameUnique(String newLoginName, String oldLoginName) {
		return userDao.isPropertyUnique("userName", newLoginName, oldLoginName);
	}

	@Transactional(readOnly = true)
	public boolean isregisterEmailUnique(String newEmail, String oldEmail) {
		return userDao.isPropertyUnique("email", newEmail, oldEmail);
	}

	@Transactional(readOnly = true)
	public boolean isRoleNameUnique(String newRoleName, String oldRoleName) {
		return roleDao.isPropertyUnique("roleName", newRoleName, oldRoleName);
	}

	/**
	 * 用户注册使用 registerUser: 适用:
	 * 
	 * @param user
	 * @exception
	 * @since 1.0.0
	 */
	public void registerUser(User user) {
		String password = user.getPassword();
		// // 加密密码
		// password =StringUtils.encodePassword(password,
		// Constants.ENC_ALGORITHM);
		user.setPassword(password);
		this.saveUser(user);
		// mimeMailService.sendRegisteredMail(user.getEmail(),user.getName(),user.getUsername(),password);
	}

	/**
	 * 修改密码使用 changePassword: 适用:
	 * 
	 * @param user
	 * @param newPassword
	 * @exception
	 * @since 1.0.0
	 */
	public void changePassword(User user, String newPassword) {
		// newPassword =StringUtils.encodePassword(newPassword,
		// Constants.ENC_ALGORITHM);
		// user.setPassword(newPassword);
		this.saveUser(user);
		// mimeMailService.sendNotificationMail(user.getEmail(),user.getName(),user.getUsername(),newPassword);
	}

	// ** ***外部用户的操作****//
	// -- Role Manager --//
	@Transactional(readOnly = true)
	public Role getRole(String id) {
		return roleDao.get(id);
	}

	@Transactional(readOnly = true)
	public Role findRole(String roleName) {
		return roleDao.findUniqueBy("roleName", roleName);
	}

	@Transactional(readOnly = true)
	public List<Role> getAllRole() {
		return roleDao.getAll("id", true);
	}

	public void saveRole(Role entity) {
		roleDao.save(entity);
	}

	public void deleteRole(String id) {
		roleDao.delete(id);
	}

	// -- Authority Manager --//
	@Transactional(readOnly = true)
	public List<Authority> getAllAuthority() {
		return authorityDao.getAll();
	}

	/**
	 * 查询部门详细信息
	 * 
	 * @param id
	 * @return
	 */
	@Transactional(readOnly = true)
	public Department getDepartment(String id) {
		return departmentDao.get(id);
	}

	@Transactional(readOnly = true)
	public Department findByDepartment(String propertyName, String value) {
		// TODO Auto-generated method stub
		return departmentDao.findUniqueBy(propertyName, value);
	}

	@Transactional(readOnly = true)
	public List<Department> getDepartment() {
		return departmentDao.find();
	}

	@Transactional(readOnly = true)
	public boolean isDepCodeUnique(String newDepCode, String oldDepCode) {
		return departmentDao
				.isPropertyUnique("depCode", newDepCode, oldDepCode);
	}

	/**
	 * 保存部门信息
	 * 
	 * @param entity
	 */
	public void saveDepartment(Department entity) {
		departmentDao.save(entity);
	}

	@Transactional(readOnly = true)
	public List<Department> findDeptList(QueryFilter queryfilters) {
		// TODO Auto-generated method stub
		return departmentDao.find(queryfilters);
	}

	/**
	 * 删除部门信息
	 * 
	 * @param id
	 */
	public void deleteDepartment(String id) {
		departmentDao.delete(id);
	}

	/**
	 * 使用属性过滤条件查询部门.
	 */
	@Transactional(readOnly = true)
	public Page<Department> searchDepartment(final Page<Department> page,
			final QueryFilter filters) {
		return departmentDao.findPage(page, filters);
	}

	/**
	 * 查询子部门
	 * 
	 * @param propertyName
	 * @param value
	 */
	@Transactional(readOnly = true)
	public List<Department> findDeptList(String propertyName, String value) {
		// TODO Auto-generated method stub
		return departmentDao.findBy(propertyName, value);
	}

	/**
	 * 多表链接查询
	 * 
	 * @param page
	 * @param queryfilters
	 * @return
	 */
	@Transactional(readOnly = true)
	public Page<Department> findPageDept(final Page<Department> page,
			final QueryFilter queryfilters) {
		// TODO Auto-generated method stub
		return departmentDao.findPage(page, queryfilters);
	}

	/**
	 * 查询单位信息
	 * 
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<Organization> getOrganization() {
		return organizationDao.find();
	}

	@Transactional(readOnly = true)
	public Organization getOrganization(String id) {
		return organizationDao.get(id);
	}

	@Transactional(readOnly = true)
	public List<Organization> getAll(String orgName) {
		return organizationDao.likeBy("orgName", orgName);
	}

	/**
	 * 查询内部单位信息
	 * 
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<InsideOrganization> getInsideOrganization() {
		return insideOrganizationDao.getAll();
	}

	@Transactional(readOnly = true)
	public InsideOrganization getInsideOrganization(String id) {
		return insideOrganizationDao.get(id);
	}

	public void deleteInsideOrganization(String id) {
		insideOrganizationDao.delete(id);
	}

	public void saveInsideOrganization(InsideOrganization entity) {
		insideOrganizationDao.save(entity);
	}

	@Transactional(readOnly = true)
	public Page<InsideOrganization> searchInsideOrganization(
			final Page<InsideOrganization> page, final QueryFilter queryfilter) {
		return insideOrganizationDao.findPage(page, queryfilter);
	}

	@Transactional(readOnly = true)
	public boolean isOrgNumUnique(String newOrgNum, String oldOrgNum) {
		return organizationDao.isPropertyUnique("orgNum", newOrgNum, oldOrgNum);
	}

	@Transactional(readOnly = true)
	public boolean isOrgNameUnique(String newOrgName, String oldOrgName) {
		return organizationDao.isPropertyUnique("orgName", newOrgName,
				oldOrgName);
	}

	/**
	 * 查询外部单位信息
	 * 
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<ExternalOrganization> getExternalOrganization() {
		return externalOrganizationDao.getAll();
	}

	@Transactional(readOnly = true)
	public ExternalOrganization getExternalOrganization(String id) {
		return externalOrganizationDao.get(id);
	}

	public void deleteExternalOrganization(String id) {
		externalOrganizationDao.delete(id);
	}

	public void saveExternalOrganization(ExternalOrganization entity) {
		externalOrganizationDao.save(entity);
	}

	@Transactional(readOnly = true)
	public Page<ExternalOrganization> searchExternalOrganization(
			final Page<ExternalOrganization> page, final QueryFilter filters) {
		return externalOrganizationDao.findPage(page, filters);
	}

	/**
	 * 删除单位
	 * 
	 * @param id
	 */
	public void deleteOrganization(String id) {
		organizationDao.delete(id);
	}

	/**
	 * 保存单位信息
	 * 
	 * @param entity
	 */
	public void saveOrganization(Organization entity) {
		organizationDao.save(entity);

	}

	/**
	 * 使用属性过滤条件查询单位.
	 */
	@Transactional(readOnly = true)
	public Page<Organization> searchOrganization(final Page<Organization> page,
			final QueryFilter filters) {
		return organizationDao.findPage(page, filters);
	}

	/**
	 * 根据单位名称查询单位.
	 */
	@Transactional(readOnly = true)
	public List<Organization> likeOrg(final String propertyName,
			final String value) {
		return organizationDao.likeBy(propertyName, value);
	}

	/**
	 * 保存权限信息
	 * 
	 * @param entity
	 */
	public void saveAuthority(Authority entity) {
		authorityDao.save(entity);
	}

	/**
	 * 查询权限信息
	 * 
	 * @param id
	 * @return
	 */
	@Transactional(readOnly = true)
	public Authority getAuthorityById(String id) {
		return authorityDao.get(id);
	}

	@Transactional(readOnly = true)
	public List<Authority> getAll() {
		return authorityDao.getAll();
	}

	@Transactional(readOnly = true)
	public Page<Authority> searchAuthority(final Page<Authority> page,
			final QueryFilter filters) {
		return authorityDao.findPage(page, filters);
	}

	public void delete(String id) {
		authorityDao.delete(id);
	}

	// *******操作UserDept*************//
	/**
	 * 保存
	 * 
	 * @param entity
	 */
	public void save(UserDepartment entity) {
		userDepartmentDao.save(entity);
	}

	/**
	 * 删除
	 */
	public void deleteUserDept(String id) {

		userDepartmentDao.delete(id);
	}

	@Transactional(readOnly = true)
	public List<UserDepartment> getUserDepartmentAll() {
		return userDepartmentDao.getAll();
	}

	@Transactional(readOnly = true)
	public UserDepartment getUserDepartmentById(String id) {
		return userDepartmentDao.get(id);
	}

	@Transactional(readOnly = true)
	public Page<UserDepartment> searchUserDepartment(
			final Page<UserDepartment> page, final QueryFilter filters) {
		return userDepartmentDao.findPage(page, filters);
	}

	/**
	 * 查找同一父部门下的所有子部门和人员
	 * 
	 * @param deptId
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<Department> getChildrenDept(String deptId) {
		// TODO Auto-generated method stub
		return departmentDao.findBy("fid", deptId);
	}

	// /操作用户对象
	/**
	 * 根据部门查询用户
	 * 
	 * @param depId
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<User> searchUserByDepId(String depId) {
		Department department = departmentDao.get(depId);
		List<UserDepartment> userDepartments = userDepartmentDao.findBy(
				"department", department);
		List<User> list = new ArrayList<User>();
		for (UserDepartment userDepartment : userDepartments) {

			list.add(userDepartment.getUser());
		}
		return list;
	}

	/**
	 * 
	 * findInsideUser: 适用:查找内部用户
	 * 
	 * @param page
	 * @param queryfilter
	 * @return
	 * @exception
	 * @since 1.0.0
	 */
	@Transactional(readOnly = true)
	public Page<User> findInsideUser(Page<User> page, QueryFilter queryfilter) {
		// TODO Auto-generated method stub
		return userDao.findPage(page, queryfilter);
	}

	/**
	 * 
	 * findInsideUser: 适用:查找外部用户
	 * 
	 * @param page
	 * @param queryfilter
	 * @return
	 * @exception
	 * @since 1.0.0
	 */
	@Transactional(readOnly = true)
	public Page<User> findPageUser(Page<User> page, QueryFilter queryfilter) {
		// TODO Auto-generated method stub
		return userDao.findPage(page, queryfilter);
	}

	/**
	 * 
	 * findOutUser: 适用:查找外部用户
	 * 
	 * @param page
	 * @param queryfilter
	 * @return
	 * @exception
	 * @since 1.0.0
	 */
	@Transactional(readOnly = true)
	public Page<User> findOutUser(Page<User> page, QueryFilter queryfilter) {
		// TODO Auto-generated method stub
		return userDao.findPage(page, queryfilter);
	}

	/**
	 * 根据类型分页获取单位信息
	 * 
	 * @param page
	 * @param queryfilter
	 * @return
	 */
	public Page<Organization> searchTypeOrganization(
			final Page<Organization> page, final QueryFilter queryfilter) {
		// TODO Auto-generated method stub
		return organizationDao.findPage(page, queryfilter);
	}

	/**
	 * 根据类型查找单位信息
	 * 
	 * @param page
	 * @param queryfilter
	 * @return
	 */
	public List<Organization> searchTypeOrgAuto(final QueryFilter queryfilter) {
		// TODO Auto-generated method stub

		return organizationDao.find(queryfilter);
	}

	/**
	 * 验证邮箱是否重复
	 * 
	 * @param email
	 * @param oldEmail
	 * @return
	 */
	public boolean isEmail(String email, String oldEmail) {
		// TODO Auto-generated method stub
		return userDao.isPropertyUnique("email", email, oldEmail);
	}

	@Transactional(readOnly = true)
	public List<UserDepartment> findUserDept(String property, String value) {
		return userDepartmentDao.findBy(property, value);
	}
	
	//查找部门下的所有人员
	@Transactional(readOnly = true)
	public List<UserDepartment> findDeptUser(QueryFilter queryfilters) {
		// TODO Auto-generated method stub
		return userDepartmentDao.find(queryfilters);
	}

	/* 操作人员资质 */
	/**
	 * 
	 * findByUserQua: 适用:按照属性名或属性值查找单条信息
	 * 
	 * @param string
	 * @param id
	 * @return
	 * @exception
	 * @since 1.0.0
	 */

	@Transactional(readOnly = true)
	public UserQualification findByUserQua(String propertyName, String value) {
		// TODO Auto-generated method stub
		return userQuaDao.findUniqueBy(propertyName, value);
	}

	/**
	 * 
	 * findPageUserQua: 适用:按照属性名或属性值查找一组对象
	 * 
	 * @param propertyName
	 * @param value
	 * @return
	 * @exception
	 * @since 1.0.0
	 */
	@Transactional(readOnly = true)
	public List<UserQualification> findListUserQua(String propertyName,
			String value) {
		// TODO Auto-generated method stub
		return userQuaDao.findBy(propertyName, value);
	}

	/**
	 * 
	 * findPageUserQua: 适用:按照属性值分页获取对象
	 * 
	 * @param queryfilter
	 * @param page
	 * @return
	 * @exception
	 * @since 1.0.0
	 */
	@Transactional(readOnly = true)
	public Page<UserQualification> findPageUserQua(
			final QueryFilter queryfilter, final Page<UserQualification> page) {
		return userQuaDao.findPage(page, queryfilter);
	}

	public void saveUserQualification(UserQualification userQualification) {
		userQuaDao.save(userQualification);
	}

	public void deleteUserQualification(String id) {
		userQuaDao.delete(id);
	}

	@Autowired
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Autowired
	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}

	@Autowired
	public void setAuthorityDao(AuthorityDao authorityDao) {
		this.authorityDao = authorityDao;
	}

	@Autowired
	public void setDepartmentDao(DepartmentDao departmentDao) {
		this.departmentDao = departmentDao;
	}

	@Autowired
	public void setOrganizationDao(OrganizationDao organizationDao) {
		this.organizationDao = organizationDao;
	}

	@Autowired
	public void setUserDepartmentDao(UserDepartmentDao userDepartmentDao) {
		this.userDepartmentDao = userDepartmentDao;
	}

	@Autowired
	public void setInsideOrganizationDao(
			InsideOrganizationDao insideOrganizationDao) {
		this.insideOrganizationDao = insideOrganizationDao;
	}

	@Autowired
	public void setExternalOrganizationDao(
			ExternalOrganizationDao externalOrganizationDao) {
		this.externalOrganizationDao = externalOrganizationDao;
	}

	@Autowired
	public void setUserQuaDao(UserQualificationDao userQuaDao) {
		this.userQuaDao = userQuaDao;
	}

	@Transactional(readOnly = true)
	public Organization getOrg(String propertyName, String value) {
		// TODO Auto-generated method stub
		return organizationDao.findUniqueBy(propertyName, value);
	}

	
	/**
	 * 根据用户名查询姓名
	 * getNameByUserName:
	 * 适用:
	 * @param userName
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	public User getNameByUserName(String userName){
		return userDao.findUniqueBy("userName", userName);
	}

}
